package haha.life.normal;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.beanutils.BeanUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;

public class CommonConvertUtils {
    public CommonConvertUtils() {
    }

    private static final String UNDERLINE = "_";

    public static String getUnderline() {
        return UNDERLINE;
    }

    /*----------数组类型字符串转数组---------------*/
    public static String[] getStringArrToArr(String stringArr) {
        String  realArrStr=stringArr.substring(1, stringArr.length()-1);
        String[] arr = realArrStr.split(",");
        return arr;
    }
    /*----------json数据和对象的转换---------------*/

    /**
     * 功能描述：将JSON数据转换成指定的java对象
     *
     * @param jsonData JSON数据
     * @param clazz    指定的java对象
     * @return 指定的java对象
     */
    public static <T> T getJsonToBean(String jsonData, Class<T> clazz) {
        return JSON.parseObject(jsonData, clazz);
    }

    /**
     * 功能描述：将java对象转换成JSON数据
     *
     * @param object java对象
     * @return JSON数据
     */
    public static String getBeanToJson(Object object) {
        return JSON.toJSONString(object);
    }

    /**
     * 功能描述：将JSON数据转换成指定的java对象列表
     *
     * @param jsonData JSON数据
     * @param clazz    指定的java对象
     * @return List<T>
     */
    public static <T> List<T> getJsonToList(String jsonData, Class<T> clazz) {
        return JSON.parseArray(jsonData, clazz);
    }

    /**
     * 功能描述：将List 转换成Json
     *
     * @param object list数据
     * @return List<T>
     */
    public static String getListToJson(Object object) {
        return JSON.toJSONString(object);
    }

    /**
     * 功能描述：把JSON数据转换成较为复杂的List<Map<String, Object>>
     *
     * @param jsonData JSON数据
     * @return List<Map < String, Object>>
     */
    public static List<Map<String, Object>> getJsonToListMap(String jsonData) {
        return JSON.parseObject(jsonData, new TypeReference<List<Map<String, Object>>>() {
        });
    }

    /*----------Map和对象的转换---------------*/

    /**
     * 功能描述：将 Map 转化为JavaBean
     *
     * @param map
     * @param T
     * @return
     * @throws Exception
     */
    public static <T> T convertMapToBean(Map<String, Object> map, Class<T> T) throws Exception {
        if (map == null || map.size() == 0) {
            return null;
        }
        //获取map中所有的key值，全部更新成大写，添加到keys集合中,与mybatis中驼峰命名匹配
        Object mvalue = null;
        Map<String, Object> newMap = new HashMap<>();
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            String key = it.next().getKey();
            mvalue = map.get(key);
            if (key.indexOf(UNDERLINE) != -1) {
                key = key.replaceAll(UNDERLINE, "");
            }
            newMap.put(key.toUpperCase(Locale.US), mvalue);
        }

        BeanInfo beanInfo = Introspector.getBeanInfo(T);
        T bean = T.newInstance();
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0, n = propertyDescriptors.length; i < n; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            String upperPropertyName = propertyName.toUpperCase();

            if (newMap.keySet().contains(upperPropertyName)) {
                Object value = newMap.get(upperPropertyName);
                //这个方法不会报参数类型不匹配的错误。
                BeanUtils.copyProperty(bean, propertyName, value);
            }
        }
        return bean;
    }


    /**
     * 功能描述：将 JavaBean 对象转化为Map
     *
     * @param bean
     * @return
     * @throws IntrospectionException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static Map<String, Object> convertBeanToMap(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        Class<? extends Object> type = bean.getClass();
        Map<String, Object> returnMap = new HashMap<>();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);

        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!"class".equals(propertyName)) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null) {
                    returnMap.put(propertyName, result);
                } else {
                    returnMap.put(propertyName, null);
                }
            }
        }
        return returnMap;
    }

    /**
     * 功能描述：将 List<Map>对象转化为List<JavaBean>
     *
     * @param listMap
     * @param T
     * @return
     * @throws Exception
     */
    public static <T> List<T> convertListMapToListBean(List<Map<String, Object>> listMap, Class<T> T) throws Exception {
        List<T> beanList = new ArrayList<>();
        if (listMap != null && !listMap.isEmpty()) {
            for (int i = 0, n = listMap.size(); i < n; i++) {
                Map<String, Object> map = listMap.get(i);
                T bean = convertMapToBean(map, T);
                beanList.add(bean);
            }
            return beanList;
        }
        return beanList;
    }

    /**
     * 功能描述：将 List<JavaBean>对象转化为List<Map>
     *
     * @param beanList
     * @return
     * @throws Exception
     */
    public static <T> List<Map<String, Object>> convertListBeanToListMap(List<T> beanList, Class<T> T) throws Exception {
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (int i = 0, n = beanList.size(); i < n; i++) {
            Object bean = beanList.get(i);
            Map<String, Object> map = convertBeanToMap(bean);
            mapList.add(map);
        }
        return mapList;
    }

    /*----------Map和对象的转换 利用反射---------------*/
    /**
     * 将 Map 转化为 javaBean对象 利用反射实现
     * @param map
     * @param beanClass
     * @return
     * @throws Exception
     */
    public static Object convertMapToBeanOfReflex(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null) {
            return null;
        }

        Object obj = beanClass.newInstance();

        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }

            boolean accessFlag = field.isAccessible();
            field.setAccessible(true);// 允许通过反射访问该字段
            field.set(obj, map.get(field.getName()));
            field.setAccessible(accessFlag);
        }

        return obj;
    }

    /**
     * 将 javaBean 转化为Map,利用反射实现 利用反射实现
     * <li>空属性不转换
     * <li>超过10万条数据不建议使用
     * @param obj
     * @return
     * @throws Exception
     */
    public static Map<String, Object> convertBeanToMapOfReflex(Object obj) throws Exception {

        if (obj == null) {
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (int i = 0, len = fields.length; i < len; i++) {
            String varName = fields[i].getName();
            boolean accessFlag = fields[i].isAccessible();
            fields[i].setAccessible(true);// 允许通过反射访问该字段

            Object valueObj = fields[i].get(obj);
            if (valueObj != null) {
                map.put(varName, valueObj);
            }
            fields[i].setAccessible(accessFlag);
        }
        return map;
    }
    /**
     功能描述：将JSON[]转换成String[]
     *
     * @return List<T>
     */
    public  static String[]  JsonArrToStringArr(JSONArray array) {
        Object[] src = array.toArray();
        String[] target = new String[src.length];
        System.arraycopy(src, 0, target, 0, src.length);
        return  target;
    }


    public  static String[]  ArrToStringArr(List<String> array) {
        Object[] src = array.toArray();
        String[] target = new String[src.length];
        System.arraycopy(src, 0, target, 0, src.length);
        return  target;
    }

    /*------------------xml---------------------------*/
    // XML格式字符串获取指定标签值
    public static Map<String, String> getXMLStringValue(String result){
        Map<String, String> rm = new HashMap<String, String>();
        StringReader sr = new StringReader(result); 	// result数据源：XML格式字符串
        InputSource is = new InputSource(sr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        org.w3c.dom.Document document = null;
        try {
            document = builder.parse(is);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Element rootElement = document.getDocumentElement();
        NodeList nodes = rootElement.getChildNodes();	// 一级标签

        for (int i = 0; i < nodes.getLength(); i++) {

            Node node = nodes.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                if (node.getFirstChild() != null) {
                    rm.put(node.getNodeName(), node.getFirstChild().getNodeValue());
                }
                NodeList nodeList = node.getChildNodes();	// 二级标签
                if (nodeList != null) {
                    for (int j = 0; j < nodeList.getLength(); j++) {
                        Node childnode1 = nodeList.item(j);
                        if (childnode1 instanceof Element) {
                            if (childnode1.getFirstChild() != null) {
                                rm.put(childnode1.getNodeName(), childnode1.getFirstChild().getNodeValue());
                            }
                            NodeList nodeList1 = childnode1.getChildNodes();	// 三级标签

                            if (nodeList1 != null) {
                                for (int k = 0; k < nodeList1.getLength(); k++) {
                                    Node childnode2 = nodeList1.item(k);
                                    if (childnode2 instanceof Element) {
                                        if (childnode2.getFirstChild() != null) {
                                            rm.put(childnode2.getNodeName(), childnode2.getFirstChild().getNodeValue());
                                        }
                                        NodeList nodeList2 = childnode2.getChildNodes();

                                        // 当有四级或以上标签时，在此重复写解析代码
                                    }
                                }

                            }
                        }
                    }

                }
            }
        }
        return rm;
    }
}
